package com.cjd.common.okhttp3

import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okio.Buffer
import okio.BufferedSink
import okio.ForwardingSink
import okio.Okio
import java.io.IOException

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/11/7
 * description 文件上传进度回调
 */
class MultipartUploadProgressBody(
    private val multipartBody: MultipartBody,
    var listener: ((total: Long, currentLength: Long) -> Unit)? = null
) : RequestBody() {


    private var mCurrentLength: Long = 0

    fun setProgressListener(listener: ((total: Long, currentLength: Long) -> Unit)) {
        this.listener = listener
    }

    override fun contentType(): MediaType? = multipartBody.contentType()

    override fun contentLength(): Long = multipartBody.contentLength()

    override fun writeTo(sink: BufferedSink) {


        //这里需要另一个代理类来获取写入的长度
        val forwardingSink = object : ForwardingSink(sink) {

            val totalLength = contentLength()

            @Throws(IOException::class)
            override fun write(source: Buffer, byteCount: Long) {

                //这里可以获取到写入的长度
                mCurrentLength += byteCount
                //回调进度
                listener?.invoke(totalLength, mCurrentLength)

                super.write(source, byteCount)
            }
        }

        //转一下
        val bufferedSink = Okio.buffer(forwardingSink)
        //写数据
        multipartBody.writeTo(bufferedSink)
        //刷新一下数据
        bufferedSink.flush()
    }
}